package com.yonyougov.devops.cruxcisupport.k8s.rest;

import com.yonyougov.devops.cruxcisupport.k8s.Constant;
import com.yonyougov.devops.cruxcisupport.k8s.secret.SecretRepository;
import com.yonyougov.devops.cruxcisupport.k8s.secret.SecretRequest;
import com.yonyougov.devops.fwc.api.dto.BaseResponseDto;
import io.swagger.annotations.Api;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "调用k8sAPI创建相关资源")
@Slf4j
@RestController
@RequestMapping("/api/v2/kubernetes/secret")
public class K8sSecretController {
    private final SecretRepository secretRepository;
    @Value("${k8s.dockerconfigjson}")
    private String DOCKERCONFIGJSON;

    public K8sSecretController(SecretRepository secretRepository) {
        this.secretRepository = secretRepository;
    }

    @PostMapping(value = "/replace")
    @SneakyThrows
    public BaseResponseDto createPod(@RequestBody @Valid ReplaceSecretRequest request) {
        secretRepository.delete(request.getName(), request.getNamespace());
        Thread.sleep(5000);

        Map<String, String> secretMapDatas = new HashMap<>();
        secretMapDatas.put(Constant.SECRET_MAP_KEY, DOCKERCONFIGJSON);
        SecretRequest secretRequest = SecretRequest.builder().
                name(request.getName()).
                nameSpace(request.getNamespace()).
                data(secretMapDatas).
                build();
        secretRepository.createOrReplace(secretRequest);
        return BaseResponseDto.getSuccessInstance();
    }


}
